package com.linrung.sf.scheduler.zwwx;

import cn.hutool.setting.Setting;
import com.linrung.core.cache.ICacheClient;
import com.linrung.core.utils.JsonUtils;
import com.linrung.core.utils.StringTools;
import com.linrung.platform.job.jobConfig.JobConfigEntity;
import com.linrung.scheduler.core.AbstractJobBusinessService;
import com.linrung.sf.scheduler.zwwx.entity.*;
import com.linrung.sf.scheduler.zwwx.jms.ZWWXMsgProductorService;
import com.linrung.sf.scheduler.zwwx.service.WarnMessageSendService;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.*;

@Service(value="EventHandleOutTimeService")
public class EventHandleOutTimeService extends AbstractJobBusinessService{
	
	private static Logger logger = Logger.getLogger(EventHandleOutTimeService.class);
	@Autowired
	private WarnMessageSendService warnMessageSendService;
	@Autowired
	private ZWWXMsgProductorService zwwxMsgProductorService;

	private Integer agentId = null;
	//预警原因
	private String warnReasonTpl1 = null;
	//消息内容
	private String msgContentTpl1 = null;
	//预警原因
	private String warnReasonTpl2 = null;
	//消息内容
	private String msgContentTpl2 = null;
	//预警原因
	private String warnReasonTpl3 = null;
	//消息内容
	private String msgContentTpl3 = null;
	//预警原因
	private String warnReasonTpl5 = null;
	//消息内容
	private String msgContentTpl5 = null;
	private int successCount = 0;
	private int noUserWxIdCount = 0;
	private int otherErrorCount = 0;
	private Setting _setting = null;

	@Override
	public String execute(JobConfigEntity jobConfig) {
		long time1 = System.currentTimeMillis();
		logger.info("开始逾期监测与消息提醒==============");

		agentId = Integer.parseInt(jobConfig.getParams().get("AGENTID"));
		if(agentId==null) {
			logger.error("请在定时任务参数配置中配置【AGENTID】参数");
			return null;
		}
		warnReasonTpl1 = jobConfig.getParams().get("WARNREASONTPL1");
		if(warnReasonTpl1==null) {
			logger.error("请在定时任务参数配置中配置【WARNREASONTPL1】参数");
			return null;
		}

		msgContentTpl1 = jobConfig.getParams().get("MSGCONTENTTPL1");
		if(msgContentTpl1==null) {
			logger.error("请在定时任务参数配置中配置【MSGCONTENTTPL1】参数");
			return null;
		}
		warnReasonTpl2 = jobConfig.getParams().get("WARNREASONTPL2");
		if(warnReasonTpl2==null) {
			logger.error("请在定时任务参数配置中配置【WARNREASONTPL2】参数");
			return null;
		}

		msgContentTpl2 = jobConfig.getParams().get("MSGCONTENTTPL2");
		if(msgContentTpl2==null) {
			logger.error("请在定时任务参数配置中配置【MSGCONTENTTPL2】参数");
			return null;
		}
		warnReasonTpl3 = jobConfig.getParams().get("WARNREASONTPL3");
		if(warnReasonTpl3==null) {
			logger.error("请在定时任务参数配置中配置【WARNREASONTPL3】参数");
			return null;
		}

		msgContentTpl3 = jobConfig.getParams().get("MSGCONTENTTPL3");
		if(msgContentTpl3==null) {
			logger.error("请在定时任务参数配置中配置【MSGCONTENTTPL3】参数");
			return null;
		}
		warnReasonTpl5 = jobConfig.getParams().get("WARNREASONTPL5");
		if(warnReasonTpl5==null) {
			logger.error("请在定时任务参数配置中配置【WARNREASONTPL5】参数");
			return null;
		}

		msgContentTpl5 = jobConfig.getParams().get("MSGCONTENTTPL5");
		if(msgContentTpl5==null) {
			logger.error("请在定时任务参数配置中配置【MSGCONTENTTPL5】参数");
			return null;
		}
		successCount = 0;
		noUserWxIdCount = 0;
		otherErrorCount = 0;
		try {
			if(_setting == null){
				_setting = new Setting("jms.template.setting");
			}
			if(_setting.isEmpty()){
				logger.error("setting配置为空！");
			}
		}catch (Exception e){
			logger.error("取setting配置："+e.getMessage(), e);
		}finally {
			sendMessageGroup(jobConfig);
		}
		long time2 = System.currentTimeMillis();
		logger.info(String.format("结束逾期监测与消息提醒==============，共花费 = %d ms, 成功发送JMS = %d, 用户没绑定微信失败 = %d, 其他验证性错误 = %d", time2-time1, successCount, noUserWxIdCount, otherErrorCount));
		return null;
	}
	
	/**
	 * 推送待办的消息
	 * @param jobConfig
	 */
	private void sendMessageGroup(JobConfigEntity jobConfig){
		//生成待发送消息
		warnMessageSendService.genAppealAcceptOutTime(warnReasonTpl1, msgContentTpl1);
		warnMessageSendService.genAppealHandleOutTime(warnReasonTpl2, msgContentTpl2);
		warnMessageSendService.genWorkTaskHandleOutTime(warnReasonTpl3, msgContentTpl3);
		warnMessageSendService.genPreAppealHandleOutTime(warnReasonTpl5, msgContentTpl5);
		warnMessageSendService.genWarnNoticeMessage();
		warnMessageSendService.genSuperviseNoticeMessage();//临时使用，后续需优化或停用

		//获取待发消息
		List<ZwwxMessageEntity> msgList = warnMessageSendService.loadNoNoticeMessageList();

		int msgListSize = 0;
		if(msgList != null) {
			msgListSize = msgList.size();
		}
		logger.info(String.format("本次要发送的逾期消息总条数 = %d", msgListSize));

		//jms发送列表
		List<JMSSendParamVO> sendList = new ArrayList<JMSSendParamVO>();
		//发送消息
		for(ZwwxMessageEntity msgr : msgList){
			//发送JMS消息
			String pfMsgReceiveId = msgr.getId();
			if(StringUtils.isBlank(msgr.getReceiverSyncUserId()) || msgr.getReceiverSyncUserId().equals("-99")){
				logger.error(msgr.getReceiverId() + "用户，未同步粤政易用户ID，无法推送！");
				noUserWxIdCount++;
				warnMessageSendService.updateReceiverWxSendStateById(msgr.getId(), "2");
				continue;
			}
			if(StringUtils.isBlank(msgr.getTitle())) {
				otherErrorCount++;
				logger.error(msgr.getReceiverId() + ",标题为空了，无法推送！");
				warnMessageSendService.updateReceiverWxSendStateById(msgr.getId(), "2");
				continue;
			}
			if(StringUtils.isNotEmpty(msgr.getReceiverSyncUserId())){
				TextCardEntity card = setCard(msgr);
				//消息
				TextMessageEntity message = new TextMessageEntity();
				message.setTouser(msgr.getReceiverSyncUserId());
				message.setToparty("");
				message.setMsgtype(ZwwxMsgType.text.getValue());
				message.setTotag("");
				message.setAgentid(agentId);
				JSONObject text = new JSONObject();
				text.put("content",card.getDescription());
				message.setText(text);
				String zwsxMsgcontent = JsonUtils.converJsonStr(message, null);
				JMSSendParamVO jmsSendParamVO = new JMSSendParamVO();
				jmsSendParamVO.setPfMsgReceiveId(pfMsgReceiveId);
				jmsSendParamVO.setZwsxMsgcontent(zwsxMsgcontent);
				sendList.add(jmsSendParamVO);
				warnMessageSendService.updateReceiverWxSendStateById(msgr.getId(), "1");
				successCount++;
			}
		}
		//等上面的数据库操作完成，一次行发送JMS，保证消费者消费时间长，数据库锁太久
		zwwxMsgProductorService.send(sendList);
	}

	/**
	 * 设置卡面内容
	 * @param msgr
	 * @return
	 */
	private TextCardEntity setCard(ZwwxMessageEntity msgr){
		TextCardEntity card = new TextCardEntity();
		Map<String, String> templates = _setting.getMap("COMMON.YPA.NOTICE.TEXT");
		String tpl = StringTools.getValue(templates.get("template"), null);
		String description = formatDescription(tpl, msgr.getSource(),msgr.getTitle());
		card.setDescription(description);
		return card;
	}

	/**
	 * 计算卡片消息的字节，不能超过512, 不然优先截掉标题的字数
	 * @param tpl
	 * @param title
	 * @param subTitle
	 * @return
	 */
	private String formatDescription(String tpl, String title, String subTitle){
		String description = String.format(tpl, title, subTitle);
		String tempTitle = "";
		int total = description.getBytes(StandardCharsets.UTF_8).length;
		//原定最大字节512，但行数超过六行，也会隐藏后面的日期信息，所以限到414
		while (total > 414){
			int etc = (total - 414 + 3) / 4;
			subTitle = subTitle.substring(0, title.length() - etc - 3);
			tempTitle = subTitle + "...";
			description = String.format(tpl, title, tempTitle);
			total = description.getBytes(StandardCharsets.UTF_8).length;
		}
		return description;
	}
	
}
